<?php
/**
 * 产品试戴模型
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/1/18
 * @copyright PanxSoft Inc.
 */
namespace App\Models\Products;

use App\Services\MobileApp\AppEnv;
use App\Services\Utils\ImageHelper;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * @method static self filterAppPlatform(int $type = null)
 * @property array|null previews - 缩略图 多图
 */
class TryonModel extends Model
{
    const TYPE_PC_GLASS = 1;
    const TYPE_IOS_GLASS = 2;
    const TYPE_ANDROID_GLASS = 3;

    protected $guarded = [];

    protected $table = 'tryon_model';

    protected $primaryKey = 'tryon_model_id';

    protected $appends = [
        'model_url', 'preview_url',
//        'preview_urls' // 暂时不使用，模型组还是修改
   ];

    protected $casts = [
        'previews' => 'array'
    ];

    protected $hidden = ['model', 'preview', 'previews'];

    const PLATFORM_TYPE_MAP = [
        AppEnv::PLATFORM_IOS => self::TYPE_IOS_GLASS,
        AppEnv::PLATFORM_ANDROID => self::TYPE_ANDROID_GLASS,
    ];

    public function getModelUrlAttribute()
    {
        $model_key = $this->getOriginal('model');

        return $model_key
            ? ImageHelper::toOpenCartUrl($model_key)
            : null;
    }

    public function getPreviewUrlAttribute()
    {
        $model_key = $this->getOriginal('preview');

        return $model_key
            ? ImageHelper::toOpenCartUrl($model_key)
            : null;
    }

    public function getPreviewUrlsAttribute()
    {
        if (! $this->previews) {
            return null;
        }

        return array_map(function ($model_key) {
            return ImageHelper::toOpenCartUrl($model_key);
        }, $this->previews);
    }

    /**
     * @used-by filterAppPlatform
     *
     * @param Builder $builder
     * @param int|null $type
     */
    public function scopeFilterAppPlatform(Builder $builder, int $type = null)
    {
        $builder->where('type', $type ?: self::platformMapType(AppEnv::platform()));
    }

    public static function platformMapType(?string $platform): ?int
    {
        return self::PLATFORM_TYPE_MAP[$platform] ?? null;
    }
}